<template>
  <div class="page">
    <div class="toolbar">
      <el-form :model="query" inline class="filters">
        <el-form-item label="编码"><el-input v-model="query.code" placeholder="包含匹配" /></el-form-item>
        <el-form-item label="名称"><el-input v-model="query.name" /></el-form-item>
        <el-form-item label="启用">
          <el-select v-model="query.enabled" placeholder="全部" style="width:100px">
            <el-option :value="undefined" label="全部" />
            <el-option :value="true" label="启用" />
            <el-option :value="false" label="停用" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="load">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="actions">
        <el-button type="primary" @click="openCreate">创建角色</el-button>
        <el-button @click="load">刷新</el-button>
      </div>
    </div>

    <div class="table-area">
      <el-table :data="roles" style="width:100%">
        <el-table-column prop="code" label="编码" min-width="160" />
        <el-table-column prop="name" label="名称" min-width="160" />
        <el-table-column prop="enabled" label="启用" width="100">
          <template #default="{ row }">
            <el-tag :type="row.enabled ? 'success' : 'info'">{{ row.enabled ? '启用' : '停用' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="240">
          <template #default="{ row }">
            <el-button size="small" @click="openSetMenus(row)">设置菜单权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog v-model="showDialog" title="设置角色菜单权限" width="720px" destroy-on-close>
      <div style="margin-bottom:8px">角色：{{ currentRole?.name }}（{{ currentRole?.code }}）</div>
      <el-tree
        ref="treeRef"
        :data="menuTree"
        node-key="id"
        show-checkbox
        :props="treeProps"
        default-expand-all
        style="border:1px solid var(--border-soft,#e9edf3); border-radius:8px; padding:8px;"
      />
      <template #footer>
        <el-button @click="showDialog=false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="submitSetMenus">保存</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="showCreateDialog" title="创建角色" width="520px" destroy-on-close>
      <el-form :model="createForm" :rules="createRules" ref="createFormRef" label-width="80px">
        <el-form-item label="编码" prop="code"><el-input v-model="createForm.code" /></el-form-item>
        <el-form-item label="名称" prop="name"><el-input v-model="createForm.name" /></el-form-item>
        <el-form-item label="描述"><el-input v-model="createForm.description" /></el-form-item>
        <el-form-item label="启用"><el-switch v-model="createForm.enabled" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateDialog=false">取消</el-button>
        <el-button type="primary" :loading="createSaving" @click="submitCreate">确定</el-button>
      </template>
    </el-dialog>
  </div>
  </template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { api } from '../../api/client'

type Role = { id: string; code: string; name: string; enabled: boolean }
type MenuItem = { id: string; parent_id?: string | null; name: string; path: string; icon?: string | null; order_index: number; enabled: boolean }
type MenuNode = MenuItem & { children: MenuNode[] }

const roles = ref<Role[]>([])
const query = ref<{ code?: string; name?: string; enabled?: boolean | undefined }>({ code: '', name: '', enabled: undefined })

async function load() {
  const params: any = {}
  if (query.value.code) params.code = query.value.code
  if (query.value.name) params.name = query.value.name
  if (query.value.enabled !== undefined) params.enabled = query.value.enabled
  const resp = await api.get('/roles/', { params })
  roles.value = resp.data
}

function resetQuery() {
  query.value = { code: '', name: '', enabled: undefined }
}

const showCreateDialog = ref(false)
const createSaving = ref(false)
const createForm = ref({ code: '', name: '', description: '', enabled: true })
const createFormRef = ref<FormInstance>()
const createRules: FormRules = {
  code: [{ required: true, message: '请输入编码', trigger: 'blur' }],
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
}

function openCreate() {
  createForm.value = { code: '', name: '', description: '', enabled: true }
  showCreateDialog.value = true
}

async function submitCreate() {
  if (!createFormRef.value) return
  try {
    await createFormRef.value.validate()
    createSaving.value = true
    await api.post('/roles/', { code: createForm.value.code, name: createForm.value.name, description: createForm.value.description || undefined, enabled: createForm.value.enabled })
    ElMessage.success('创建成功')
    showCreateDialog.value = false
    await load()
  } catch (err: any) {
    const msg = err?.response?.data?.detail || err?.message || '创建失败'
    ElMessage.error(msg)
  } finally { createSaving.value = false }
}

const showDialog = ref(false)
const saving = ref(false)
const currentRole = ref<Role | null>(null)
const menuTree = ref<MenuNode[]>([])
const treeRef = ref()
const treeProps = { children: 'children', label: 'name' }

function buildTree(items: MenuItem[]): MenuNode[] {
  const map: Record<string, MenuNode> = {}
  const roots: MenuNode[] = []
  items.forEach(m => { map[m.id] = { ...m, children: [] } })
  items.forEach(m => {
    const node = map[m.id]
    const pid = m.parent_id || ''
    if (pid && map[pid]) map[pid].children.push(node)
    else roots.push(node)
  })
  const idx: Record<string, number> = {}
  items.forEach(m => { idx[m.id] = m.order_index })
  const sortChildren = (n: MenuNode[]) => n.sort((a,b) => (idx[a.id]||0) - (idx[b.id]||0))
  const dfs = (n: MenuNode[]) => { sortChildren(n); n.forEach(c => dfs(c.children)) }
  dfs(roots)
  return roots
}

async function openSetMenus(row: Role) {
  currentRole.value = row
  const allMenusResp = await api.get('/menus/')
  const flat: MenuItem[] = allMenusResp.data
  menuTree.value = buildTree(flat)
  const roleMenusResp = await api.get(`/roles/${row.id}/menus`)
  const checkedIds: string[] = roleMenusResp.data.map((m: MenuItem) => m.id)
  showDialog.value = true
  // 等待树渲染后设置选中
  setTimeout(() => {
    if (treeRef.value) treeRef.value.setCheckedKeys(checkedIds)
  }, 0)
}

async function submitSetMenus() {
  if (!currentRole.value || !treeRef.value) return
  saving.value = true
  try {
    const checked: string[] = treeRef.value.getCheckedKeys()
    const half: string[] = treeRef.value.getHalfCheckedKeys?.() || []
    const all = Array.from(new Set([...(checked || []), ...(half || [])]))
    await api.post(`/roles/${currentRole.value.id}/menus`, { menu_ids: all })
    showDialog.value = false
  } finally { saving.value = false }
}

onMounted(load)
</script>

<style scoped>
.page { height: 100%; display: flex; flex-direction: column; }
.toolbar { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
.filters { flex: 1; display: flex; align-items: center; gap: 12px; }
.filters :deep(.el-form-item) { margin-bottom: 0; }
.actions { display: flex; gap: 12px; align-items: center; }
.table-area { flex: 1; min-height: 0; }
.table-area :deep(.el-table__body-wrapper) { height: 100%; overflow: auto; }
</style>
